﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GKQC.Common
{
    /// <summary>
    /// IEEE754和浮点数的相互转化
    /// </summary>
    public class IEEE754Helper
    {
        static string X2 = "X2";
        static string _0X = "0X";
        static string _0x = "0x";

        /// <summary>
        /// 把一个浮点数转化成16进制字符串
        /// </summary>
        /// <param name="paraFloat">要转化的浮点数</param>
        /// <returns>返回的字符串</returns>

        public static string floatToHex(float paraFloat)
        {
            StringBuilder sb = new StringBuilder();
            byte[] bytes = BitConverter.GetBytes(paraFloat);

            foreach (var item in bytes)
            {
                sb.Insert(0, item.ToString(X2));
            }
            return sb.Insert(0, _0X).ToString();
        }

        /// <summary>
        /// 把4个字节的16进制字符串转化成一个浮点数
        /// </summary>
        /// <param name="hexStr">待转化字符串</param>
        /// <returns>返回浮点数（转化失败返回浮点数最小值）</returns>
        public static float HexTofloat(string hexStr)
        {

            hexStr = hexStr.Trim().ToUpper();
            if (hexStr.StartsWith(_0X) || hexStr.StartsWith(_0x))
            {
                hexStr = hexStr.Substring(2);
            }
            if (hexStr.Length != 8)
            {
                return float.MinValue;
            }
            byte[] bytes = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                bytes[i] = Convert.ToByte(hexStr.Substring((3 - i) * 2, 2), 16);
            }
            return BitConverter.ToSingle(bytes, 0);
        }

        public static byte[] floatToBtyes(float paraFloat)
        {
            return BitConverter.GetBytes(paraFloat);
        }

        public static float ByteTofloat(byte[] bytes)
        {
            if (bytes.Length != 4)
            {
                return float.MinValue;
            }
            return BitConverter.ToSingle(bytes, 0);
        }
    }
}

